package com.ctshk.rpc.scenic.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.scenic.dto.ScenicResourceDTO;
import com.ctshk.rpc.scenic.dto.ScenicResourceDetailDTO;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDTO;
import com.ctshk.rpc.scenic.entity.*;
import com.ctshk.rpc.scenic.mapper.*;
import com.ctshk.rpc.scenic.req.*;
import com.ctshk.rpc.scenic.req.app.ScenicProductEsReq;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.scenic.service.IScenicResourceService;
import com.ctshk.rpc.scenic.service.IScenicResourceTicketService;
import com.ctshk.rpc.scenic.service.app.IScenicTicketEsSearchService;
import com.ctshk.rpc.system.dto.ScenicDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.ScenicDetailReq;
import com.ctshk.rpc.system.service.ISceneService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 门票产品 服务实现类
 * </p>
 *
 * @author wangcy
 * @since 2021-02-02
 */
@DubboService
@Service
public class ScenicResourceServiceImpl extends ServiceImpl<ScenicProductMapper, ScenicProduct> implements IScenicResourceService {

    @Autowired
    private ScenicProductCostStrategySpecAttrMapper strategySpecAttrMapper;

    @Autowired
    private ScenicProductCostStrategyMapper scenicProductCostStrategyMapper;

    @Autowired
    private ScenicProductCostStrategyVaildDateMapper scenicProductCostStrategyVaildDateMapper;

    @Autowired
    private ScenicProductCostStrategySpecStockMapper scenicProductCostStrategySpecStockMapper;

    @Autowired
    private ScenicProductSaleStrategyVaildDateMapper scenicProductSaleStrategyVaildDateMapper;

    @Autowired
    private ScenicProductChannelOfflineMapper scenicProductChannelOfflineMapper;

    @DubboReference
    private ISceneService sceneService;
    @Autowired
    private ScenicProductMapper scenicProductMapper;

    @Autowired
    private ScenicProductTicketMapper scenicProductTicketMapper;

    @DubboReference
    private ISysApprovalService iSysApprovalService;

    @DubboReference
    private ISysUserService iSysUserService;

    @Autowired
    IScenicResourceTicketService scenicResourceTicketService;

    @DubboReference
    private ISysPermissionService sysPermissionService;

    @DubboReference
    IScenicProductService iScenicProductService;

    @DubboReference
    IScenicTicketEsSearchService iScenicTicketEsSearchService;

    @Override
    public PageResponse<ScenicResourceDTO> queryList(ScenicResourceReq scenicResourceReq, TokenUser tokenUser) {
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            if (scenicResourceReq.getMenuId() == null) {
                throw new BusinessException(SystemError.SYSTEM_2106);
            }
            Result<List<Long>> permissionResult = sysPermissionService.queryPermission(scenicResourceReq.getMenuId(), tokenUser.getId());
            if (!permissionResult.isSuccess()) {
                SystemError result = SystemError.getDefined(permissionResult.getCode());
                throw new BusinessException(result);
            }
            scenicResourceReq.setChargeUserIds(permissionResult.getData());
            scenicResourceReq.setUserId(tokenUser.getId());
        }
        IPage<ScenicProduct> iPage = new Page<>(scenicResourceReq.getPageNo(), scenicResourceReq.getPageSize());
        QueryWrapper<ScenicProduct> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(scenicResourceReq.getCityName())) {
            queryWrapper.lambda().like(ScenicProduct::getCityName, scenicResourceReq.getCityName());
        }

        if (StringUtils.isNotBlank(scenicResourceReq.getName())) {
            queryWrapper.lambda().like(ScenicProduct::getName, scenicResourceReq.getName());
        }

        if (StringUtils.isNotBlank(scenicResourceReq.getSupplierName())) {
            queryWrapper.lambda().like(ScenicProduct::getSupplierName, scenicResourceReq.getSupplierName());
        }
        if (CollectionUtils.isNotEmpty(scenicResourceReq.getScenicIdList())) {
            queryWrapper.lambda().in(ScenicProduct::getScenicId, scenicResourceReq.getScenicIdList());
        }
        if (null != scenicResourceReq.getSourceType() && scenicResourceReq.getSourceType().intValue() != 0) {
            queryWrapper.lambda().eq(ScenicProduct::getSourceType, scenicResourceReq.getSourceType());
        }
        if (null != scenicResourceReq.getSaleStatus() && scenicResourceReq.getSaleStatus().intValue() != 0) {
            queryWrapper.lambda().eq(ScenicProduct::getSaleStatus, scenicResourceReq.getSaleStatus());
        }
        if (null != scenicResourceReq.getStatus() && scenicResourceReq.getStatus().intValue() != 0) {
            queryWrapper.lambda().eq(ScenicProduct::getStatus, scenicResourceReq.getStatus());
        }
        if (null != scenicResourceReq.getAllowPackage() && scenicResourceReq.getAllowPackage().intValue() != 0) {
            queryWrapper.lambda().eq(ScenicProduct::getAllowPackage, scenicResourceReq.getAllowPackage());
        }
        if (null != scenicResourceReq.getApprovalStatus() && scenicResourceReq.getApprovalStatus().intValue() != 0) {
            queryWrapper.lambda().eq(ScenicProduct::getApprovalStatus, scenicResourceReq.getApprovalStatus());
        }
        queryWrapper.lambda().orderByDesc(ScenicProduct::getGmtCreate);

        if (scenicResourceReq.getUserId() != null && org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(scenicResourceReq.getChargeUserIds())) {
            queryWrapper.and(e -> e.eq("create_id", scenicResourceReq.getUserId()).or().in("charge_user_id", scenicResourceReq.getChargeUserIds()));
        } else {
            if (scenicResourceReq.getUserId() != null) {
                queryWrapper.eq("create_id", scenicResourceReq.getUserId());
            }
            if (org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(scenicResourceReq.getChargeUserIds())) {
                queryWrapper.in("charge_user_id", scenicResourceReq.getChargeUserIds());
            }
        }
        IPage<ScenicProduct> insuranceIPage = baseMapper.selectPage(iPage, queryWrapper);
        if (CollectionUtils.isNotEmpty(insuranceIPage.getRecords())) {
            List<ScenicResourceDTO> scenicResourceDTOList = EntityUtil.copyList(insuranceIPage.getRecords(), ScenicResourceDTO.class);
            // 获取景点名称
            List<Long> scenicIds = scenicResourceDTOList.stream().map(ScenicResourceDTO::getScenicId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(scenicIds)) {
                Result<List<ScenicDTO>> listResult = sceneService.quertByids(org.apache.commons.lang3.StringUtils.join(scenicIds, ","));
                Map<Long, ScenicDTO> scenicMap = new HashMap<>();
                for (ScenicDTO scenic : listResult.getData()) {
                    scenicMap.put(scenic.getId(), scenic);
                }
                scenicResourceDTOList.forEach(item -> {
                    ScenicDTO scenicDTO = scenicMap.get(item.getScenicId());
                    if (null != scenicDTO) {
                        item.setScenicName(scenicDTO.getName());
                    }
                });
            }
            return new PageResponse<>(scenicResourceDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result<String> submit(ScenicProductSubmitReq scenicProductSubmitReq, TokenUser tokenUser) {
        Result<ApprovalStartDTO> result = iSysApprovalService.start(SystemBusinessType.ATTRACTION_TICKET.getCode(), SysApprovalType.ADD_TICKET.getCode(), Long.parseLong(scenicProductSubmitReq.getId()), tokenUser.getId(), null, null);
        if (result.isSuccess()) {
            ScenicProduct scenicProduct = baseMapper.selectById(scenicProductSubmitReq.getId());
            scenicProduct.setApprovalStatus(ScenicApproveType.PROCESSED.getCode());
            scenicProduct.setModifiedId(tokenUser.getId());
            scenicProduct.setGmtModified(LocalDateTime.now());
            scenicProduct.setSaleStatus(0);//售卖状态改变
            baseMapper.updateById(scenicProduct);
        } else {
            Result result1 = new Result();
            result1.setCode(result.getCode());
            result1.setMsg(result.getMsg());
            return result1;
        }
        return Result.success(scenicProductSubmitReq.getId());
    }

    @Override
    public Result<Long> check(ScenicProductCheckReq scenicProductCheckReq, TokenUser tokenUser) {
        Result<ApprovalCheckDTO> result = iSysApprovalService.check(scenicProductCheckReq.getId(), tokenUser.getId(), scenicProductCheckReq.getStatus(), scenicProductCheckReq.getComments());
        if (result.isSuccess()) {
            if (result.getData().getIsFinish()) {
                ScenicProduct scenicProduct = baseMapper.selectById(scenicProductCheckReq.getProductId());
                scenicProduct.setApprovalStatus(ScenicApproveType.PROCESSED.getCode());
                scenicProduct.setModifiedId(tokenUser.getId());
                scenicProduct.setGmtModified(LocalDateTime.now());

                if (scenicProductCheckReq.getStatus() == 3) {
                    //审批通过
                    scenicProduct.setSaleStatus(1);
                    //生成票号
                    scenicResourceTicketService.createTicket(scenicProductCheckReq.getProductId());
                }
                scenicProduct.setApprovalStatus(scenicProductCheckReq.getStatus());
                baseMapper.updateById(scenicProduct);
            }
        } else {
            Result result1 = new Result();
            result1.setCode(result.getCode());
            result1.setMsg(result.getMsg());
            return result1;
        }
        //刷新ES缓存
            CompletableFuture.runAsync(() -> {
                List<Long> ids = new ArrayList<>();
                ids.add(scenicProductCheckReq.getProductId());
                List<ScenicProductEsDTO> reqList = scenicProductMapper.selectAllProductListByids(ids);
                ScenicProductEsReq req1 = new ScenicProductEsReq();
                for(ScenicProductEsDTO dto : reqList) {
                    BeanUtils.copyProperties(dto,req1);
                    iScenicTicketEsSearchService.cacheUpdate(req1);
                    //更新redis缓存
                    iScenicTicketEsSearchService.redisUpdate(req1);
                }
            });

        return Result.success(scenicProductCheckReq.getId());
    }

    @Override
    public Result<Long> updateApi(ScenicResourceApiReq resourceApiReq) {
        super.updateBatchById(baseMapper.selectBatchIds(resourceApiReq.getIds())
                .stream()
                .filter(item -> item.getSourceType().equals(1))
                .peek(scenicProduct -> {
                    scenicProduct.setAllowPackage(resourceApiReq.getAllowPackage());
                    scenicProduct.setReserveChargeType(resourceApiReq.getReserveChargeType());
                    scenicProduct.setReserveCharge(resourceApiReq.getReserveCharge());
                    scenicProduct.setCtsChargeType(resourceApiReq.getCtsChargeType());
                    scenicProduct.setCtsCharge(resourceApiReq.getCtsCharge());
                }).collect(Collectors.toList()));
        return Result.success(resourceApiReq.getIds().get(0));
    }

    @Override
    public Result<Long> updateSaleStatus(ScenicResourceSaleReq scenicResourceSaleReq, TokenUser tokenUser) {
        baseMapper.selectBatchIds(scenicResourceSaleReq.getIds())
                .forEach(scenic -> {
                    scenic.setSaleStatus(scenicResourceSaleReq.getSaleStatus());
                    scenic.setGmtModified(LocalDateTime.now());
                    scenic.setModifiedId(tokenUser.getId());
                    baseMapper.updateById(scenic);
                });
        //刷新es缓存
            CompletableFuture.runAsync(() -> {
                List<ScenicProductEsDTO> reqList = scenicProductMapper.selectAllProductListByids(scenicResourceSaleReq.getIds());
                ScenicProductEsReq req1 = new ScenicProductEsReq();
                for(ScenicProductEsDTO dto : reqList) {
                    BeanUtils.copyProperties(dto,req1);
                    iScenicTicketEsSearchService.cacheUpdate(req1);
                }
            });
        return Result.success(scenicResourceSaleReq.getIds().get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Long> save(ScenicResourceProductReq resourceProductReq, TokenUser tokenUser) {
        List<ScenicResourceStrategyReq> scenicResourceStrategyReqs = resourceProductReq.getScenicResourceStrategy();
        //编号,库存,成本的非空校验
        for (ScenicResourceStrategyReq scenicResourceStrategyReq : scenicResourceStrategyReqs) {
            List<ScenicResourceStockReq> scenicResourceStock = scenicResourceStrategyReq.getScenicResourceStock();
            if (CollectionUtils.isNotEmpty(scenicResourceStock)) {
                for (ScenicResourceStockReq req : scenicResourceStock) {
                    if (req.getStockNumber() == null || req.getTotalStock() == 0 || req.getCostPrice().equals(BigDecimal.ZERO)) {
                        return Result.failed(SystemError.SCENIC_5024);
                    }
                }
            }
        }
        // 新增、编辑时校验传入的编号是否重复
        for (ScenicResourceStrategyReq scenicResourceStrategyReqCheck : scenicResourceStrategyReqs) {
            List<ScenicResourceStockReq> scenicResourceStockCheck = scenicResourceStrategyReqCheck.getScenicResourceStock();
            if (CollectionUtils.isNotEmpty(scenicResourceStockCheck)) {
                Map<String, Long> mapGroup = scenicResourceStockCheck.stream().collect(Collectors.groupingBy(scenicResourceStockReq -> scenicResourceStockReq.getStockNumber(), Collectors.counting()));
                for (Map.Entry<String, Long> entry : mapGroup.entrySet()) {
                    if (entry.getValue() > 1) {
                        return Result.failed(SystemError.SCENIC_5000);
                    }
                }
            }
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        Long productId;
        ScenicProduct scenicProduct = EntityUtil.copy(resourceProductReq, ScenicProduct.class);
        QueryWrapper<ScenicProduct> qw = new QueryWrapper<>();
//        qw.lambda().select(ScenicProduct::getId)
//                .eq(ScenicProduct::)
        Boolean updateFlag = (scenicProduct.getId().longValue() != 0);
        if (updateFlag) {
            QueryWrapper<ScenicProductCostStrategySpecStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", scenicProduct.getId());
            scenicProductCostStrategySpecStockMapper.delete(queryWrapper);
            scenicProduct.setGmtModified(localDateTime);
            scenicProduct.setModifiedId(tokenUser.getId());
            scenicProduct.setIsDeleted(IsDeletedCode.NO.getCode());
            productId = scenicProduct.getId();
            baseMapper.updateById(scenicProduct);
        } else {
            // 校验传入相同产品的供应商是否相同
            for (String st : scenicProductMapper.queryNameBySupplierId(resourceProductReq.getSupplierId())) {
                System.out.println(st);
                if (st.equals(resourceProductReq.getName())) {
                    return Result.failed(SystemError.SCENIC_5023);
                }
            }
            for (ScenicResourceStrategyReq scenicResourceStrategyReq : scenicResourceStrategyReqs) {
                List<ScenicResourceStockReq> scenicResourceStock = scenicResourceStrategyReq.getScenicResourceStock();
                if (CollectionUtils.isNotEmpty(scenicResourceStock)) {
                    QueryWrapper<ScenicProductCostStrategySpecStock> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().in(ScenicProductCostStrategySpecStock::getStockNumber, scenicResourceStock.stream().map(ScenicResourceStockReq::getStockNumber).collect(Collectors.toList()));
                    if (scenicProductCostStrategySpecStockMapper.selectCount(queryWrapper) > 0) {
                        return Result.failed(SystemError.SCENIC_5000);
                    }
                }
            }
            productId = SnowflakeIdWorker.nextId();
            scenicProduct.setId(productId);
            scenicProduct.setSourceType(2);
            scenicProduct.setApprovalStatus(ApprovalStatus.WAIT_SUBMIT.getCode());
            scenicProduct.setCreateId(tokenUser.getId());
            scenicProduct.setGmtCreate(localDateTime);
            scenicProduct.setGmtModified(localDateTime);
            scenicProduct.setModifiedId(tokenUser.getId());
            scenicProduct.setIsRecommend(0);
            scenicProduct.setIsDeleted(IsDeletedCode.NO.getCode());
            //生成产品编号:PM+員工編號+月日4位+時分4位+4位隨機數字
            UserDTO userDTO = iSysUserService.loadUserInfo(tokenUser.getId(), 1);
            String productCode = "PM" + userDTO.getEmployeeNumber() + LocalDate.now().format(DateTimeFormatter.ofPattern("MMdd")) + LocalTime.now().format(DateTimeFormatter.ofPattern("HHmm")) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
            scenicProduct.setProductCode(productCode.toUpperCase());
            baseMapper.insert(scenicProduct);
        }
        scenicResourceStrategyReqs.forEach(scenicResourceStrategyReq -> {
            ScenicProductCostStrategy scenicProductCostStrategy = EntityUtil.convertBean(scenicResourceStrategyReq, ScenicProductCostStrategy.class);
            scenicProductCostStrategy.setId(SnowflakeIdWorker.nextId());
            scenicProductCostStrategy.setProductId(scenicProduct.getId());
            scenicProductCostStrategy.setCreateId(tokenUser.getId());
            scenicProductCostStrategy.setGmtCreate(localDateTime);
            scenicProductCostStrategy.setModifiedId(tokenUser.getId());
            scenicProductCostStrategy.setGmtModified(localDateTime);
            scenicProductCostStrategy.setCurrency(scenicResourceStrategyReq.getCurrency());
            scenicProductCostStrategy.setIsDeleted(IsDeletedCode.NO.getCode());
            scenicProductCostStrategyMapper.insert(scenicProductCostStrategy);
            List<ScenicResourceStrategyTimeReq> timeList = scenicResourceStrategyReq.getTimeList();
            if (CollectionUtils.isNotEmpty(timeList)) {
                timeList.forEach(time -> {
                    ScenicProductCostStrategyVaildDate scenicProductCostStrategyVaildDate = EntityUtil.convertBean(time, ScenicProductCostStrategyVaildDate.class);
                    scenicProductCostStrategyVaildDate.setId(SnowflakeIdWorker.nextId());
                    scenicProductCostStrategyVaildDate.setStrategyId(scenicProductCostStrategy.getId());
                    scenicProductCostStrategyVaildDate.setProductId(scenicProduct.getId());
                    scenicProductCostStrategyVaildDateMapper.insert(scenicProductCostStrategyVaildDate);
                });
            }
            List<ScenicResourceSpecReq> specList = scenicResourceStrategyReq.getSpecList();
            if (CollectionUtils.isNotEmpty(specList)) {
                specList.stream().map(item -> {
                    ScenicProductCostStrategySpecAttr scenicProductCostStrategySpecAttr = new ScenicProductCostStrategySpecAttr();
                    scenicProductCostStrategySpecAttr.setId(SnowflakeIdWorker.nextId());
                    scenicProductCostStrategySpecAttr.setProductId(scenicProduct.getId());
                    scenicProductCostStrategySpecAttr.setStrategyId(scenicProductCostStrategy.getId());
                    scenicProductCostStrategySpecAttr.setAttributeName(item.getAttributeName());
                    scenicProductCostStrategySpecAttr.setSpecId(item.getSpecId());
                    scenicProductCostStrategySpecAttr.setSpecName(item.getSpecName());
                    return scenicProductCostStrategySpecAttr;
                }).forEach(strategySpecAttrMapper::insert);
            }

            List<ScenicResourceStockReq> scenicResourceStock = scenicResourceStrategyReq.getScenicResourceStock();
            if (CollectionUtils.isNotEmpty(scenicResourceStock)) {
                scenicResourceStock.stream().map(item -> {
                    ScenicProductCostStrategySpecStock scenicProductCostStrategySpecStock = EntityUtil.convertBean(item, ScenicProductCostStrategySpecStock.class);
                    scenicProductCostStrategySpecStock.setSurplusStock(scenicProductCostStrategySpecStock.getTotalStock());
                    scenicProductCostStrategySpecStock.setId(SnowflakeIdWorker.nextId());
                    scenicProductCostStrategySpecStock.setStrategyId(scenicProductCostStrategy.getId());
                    scenicProductCostStrategySpecStock.setProductId(scenicProduct.getId());
                    scenicProductCostStrategySpecStock.setCreateId(tokenUser.getId());
                    scenicProductCostStrategySpecStock.setGmtCreate(localDateTime);
                    scenicProductCostStrategySpecStock.setModifiedId(tokenUser.getId());
                    scenicProductCostStrategySpecStock.setGmtModified(localDateTime);
                    scenicProductCostStrategySpecStock.setIsDeleted(IsDeletedCode.NO.getCode());
                    return scenicProductCostStrategySpecStock;
                }).forEach(scenicProductCostStrategySpecStockMapper::insert);
            }
            //编辑景点时修改票号表的策略id
            if (updateFlag) {
                List<ScenicProductTicket> scenicProductTickets = scenicProductTicketMapper.queryByProductId(scenicProduct.getId());
                for (ScenicProductTicket scenicProductTicket : scenicProductTickets){
                    scenicProductTicket.setStrategyId(scenicProductCostStrategy.getId());
                    scenicProductTicketMapper.updateById(scenicProductTicket);
                }
                List<ScenicProductChannelOffline> channelOfflines = scenicProductChannelOfflineMapper.selectChannelListByProductId(scenicProduct.getId());
                for(ScenicProductChannelOffline channelOffline : channelOfflines){
                    channelOffline.setStrategyId(scenicProductCostStrategy.getId());
                    scenicProductChannelOfflineMapper.updateById(channelOffline);
                }
                ScenicProductSaleStrategyVaildDate saleStrategyVaildDate = scenicProductSaleStrategyVaildDateMapper.queryDetailById(scenicProduct.getId());
                saleStrategyVaildDate.setStrategyId(scenicProductCostStrategy.getId());
                scenicProductSaleStrategyVaildDateMapper.updateById(saleStrategyVaildDate);
            }
        });
        //刷新ES缓存
            CompletableFuture.runAsync(() -> {
                List<Long> ids = new ArrayList<>();
                ids.add(productId);
                List<ScenicProductEsDTO> reqList = scenicProductMapper.selectAllProductListByids(ids);
                ScenicProductEsReq req1 = new ScenicProductEsReq();
                for (ScenicProductEsDTO dto : reqList){
                    BeanUtils.copyProperties(dto,req1);
                    iScenicTicketEsSearchService.cacheUpdate(req1);
                    //更新redis缓存
                    iScenicTicketEsSearchService.redisUpdate(req1);
                }
            });

        return Result.success(productId);
    }

    @Override
    public Result<Long> saveAgen(ScenicProductSaveReq scenicProductSaveReq) {
        ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductSaveReq.getId());
        scenicProduct.setStartSaleTimeType(scenicProductSaveReq.getStartSaleTimeType());
        scenicProduct.setStartSaleTimeBegin(scenicProductSaveReq.getStartSaleTimeBegin());
        scenicProduct.setStartSaleTimeEnd(scenicProductSaveReq.getStartSaleTimeEnd());
        scenicProduct.setCustomerNotice(scenicProductSaveReq.getCustomerNotice());
        scenicProduct.setReserveChargeType(scenicProductSaveReq.getReserveChargeType());
        scenicProduct.setReserveCharge(scenicProductSaveReq.getReserveCharge());
        scenicProduct.setCtsChargeType(scenicProductSaveReq.getCtsChargeType());
        scenicProduct.setCtsCharge(scenicProductSaveReq.getCtsCharge());
        scenicProduct.setNeedInfo(scenicProductSaveReq.getNeedInfo());
        scenicProduct.setTicketType(scenicProductSaveReq.getTicketType());
        scenicProduct.setFetchWay(scenicProductSaveReq.getFetchWay());
        scenicProduct.setUsageMode(scenicProductSaveReq.getUsageMode());
        scenicProduct.setBookConfirm(scenicProductSaveReq.getBookConfirm());
        scenicProduct.setCancelPolicy(scenicProductSaveReq.getCancelPolicy());
        baseMapper.updateById(scenicProduct);
        return Result.success(scenicProduct.getId());
    }

    @Override
    public ScenicResourceDetailDTO quertByProductId(String productId) {
        ScenicProduct scenicProduct = baseMapper.selectById(productId);
        ScenicResourceDetailDTO scenicResourceDetailDTO = EntityUtil.convertBean(scenicProduct, ScenicResourceDetailDTO.class);
        return scenicResourceDetailDTO;
    }

    @Override
    public Result<ScenicResourceDetailDTO> detail(Long id, TokenUser currentUser) {
        ScenicProduct scenicProduct = baseMapper.selectById(id);
        ScenicResourceDetailDTO scenicResourceDetailDTO = EntityUtil.convertBean(scenicProduct, ScenicResourceDetailDTO.class);
        if (scenicProduct != null) {
            ScenicDetailReq scenicDetailReq = new ScenicDetailReq();
            scenicDetailReq.setId(scenicProduct.getScenicId());
            Result<ScenicDTO> scenicResult = sceneService.detail(scenicDetailReq);
            if (scenicResult.getData() != null) {
                ScenicDTO scenicDTO = scenicResult.getData();
                scenicResourceDetailDTO.setScenicName(scenicDTO.getName());
            }
        }
        QueryWrapper<ScenicProductCostStrategy> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ScenicProductCostStrategy::getProductId, scenicProduct.getId());

        List<ScenicProductCostStrategy> scenicProductCostStrategies = scenicProductCostStrategyMapper.selectList(queryWrapper);
        List<ScenicResourceStrategyReq> scenicResourceStrategyReqs = EntityUtil.copyList(scenicProductCostStrategies, ScenicResourceStrategyReq.class);
        scenicResourceStrategyReqs.forEach(scenicProductCostStrategy -> {
            QueryWrapper<ScenicProductCostStrategyVaildDate> dateQueryWrapper = new QueryWrapper<>();
            dateQueryWrapper.lambda().eq(ScenicProductCostStrategyVaildDate::getProductId, scenicProduct.getId());
            dateQueryWrapper.lambda().eq(ScenicProductCostStrategyVaildDate::getStrategyId, scenicProductCostStrategy.getId());
            List<ScenicProductCostStrategyVaildDate> scenicProductCostStrategyVaildDates = scenicProductCostStrategyVaildDateMapper.selectList(dateQueryWrapper);
            scenicProductCostStrategy.setTimeList(EntityUtil.copyList(scenicProductCostStrategyVaildDates, ScenicResourceStrategyTimeReq.class));

            QueryWrapper<ScenicProductCostStrategySpecAttr> attrQueryWrapper = new QueryWrapper<>();
            attrQueryWrapper.lambda().eq(ScenicProductCostStrategySpecAttr::getProductId, scenicProduct.getId());
            attrQueryWrapper.lambda().eq(ScenicProductCostStrategySpecAttr::getStrategyId, scenicProductCostStrategy.getId());
            List<ScenicProductCostStrategySpecAttr> specAttrList = strategySpecAttrMapper.selectList(attrQueryWrapper);
            scenicProductCostStrategy.setSpecList(EntityUtil.copyList(specAttrList, ScenicResourceSpecReq.class));

            QueryWrapper<ScenicProductCostStrategySpecStock> specStockQueryWrapper = new QueryWrapper<>();
            specStockQueryWrapper.lambda().eq(ScenicProductCostStrategySpecStock::getProductId, scenicProduct.getId());
            specStockQueryWrapper.lambda().eq(ScenicProductCostStrategySpecStock::getStrategyId, scenicProductCostStrategy.getId());
            List<ScenicProductCostStrategySpecStock> scenicProductCostStrategySpecStocks = scenicProductCostStrategySpecStockMapper.selectList(specStockQueryWrapper);
            scenicProductCostStrategy.setScenicResourceStock(EntityUtil.copyList(scenicProductCostStrategySpecStocks, ScenicResourceStockReq.class));
        });
        scenicResourceDetailDTO.setScenicResourceStrategy(scenicResourceStrategyReqs);
        return Result.success(scenicResourceDetailDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Long> modify(ScenicResourceProductReq resourceProductReq, TokenUser user) {
        //baseMapper.deleteById(resourceProductReq.getId());
        QueryWrapper<ScenicProductCostStrategyVaildDate> dateQueryWrapper = new QueryWrapper<>();
        dateQueryWrapper.lambda().eq(ScenicProductCostStrategyVaildDate::getProductId, resourceProductReq.getId());
        scenicProductCostStrategyVaildDateMapper.delete(dateQueryWrapper);

        QueryWrapper<ScenicProductCostStrategySpecAttr> attrQueryWrapper = new QueryWrapper<>();
        attrQueryWrapper.lambda().eq(ScenicProductCostStrategySpecAttr::getProductId, resourceProductReq.getId());
        strategySpecAttrMapper.delete(attrQueryWrapper);

        QueryWrapper<ScenicProductCostStrategySpecStock> specStockQueryWrapper = new QueryWrapper<>();
        specStockQueryWrapper.lambda().eq(ScenicProductCostStrategySpecStock::getProductId, resourceProductReq.getId());
        scenicProductCostStrategySpecStockMapper.delete(specStockQueryWrapper);

        QueryWrapper<ScenicProductCostStrategy> strategyQueryWrapper = new QueryWrapper<>();
        strategyQueryWrapper.lambda().eq(ScenicProductCostStrategy::getProductId, resourceProductReq.getId());
        scenicProductCostStrategyMapper.delete(strategyQueryWrapper);
        return save(resourceProductReq, user);
    }
}
